package servlets;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import servlet.UploadPicture;
import exception.ValidationException;

/**
 * Servlet implementation class UploadPhoto.
 * L'implementation pour mettre un image, sauf qu'on ne se
 * sert pas.
 */
public class UploadPhoto extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadPhoto() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		// TODO Auto-generated method stub
		   String user = (String)req.getSession().getAttribute("id");
	        System.out.println("User: "+ user);
	        if (!user.isEmpty()) {
	            try{
	                String adressePicture = null;
	                String idEvent = null;
	                String redir = null;
	                FileItemFactory factory = new DiskFileItemFactory();
	           ServletFileUpload upload = new ServletFileUpload(factory);
	           List<?> items = null;
	           try {
	                   items = upload.parseRequest(req);
	           } catch (Exception e) {
	                   //e.printStackTrace();
	           }
	           Iterator<?> itr = items.iterator();
	           while (itr.hasNext()) {
	           FileItem item = (FileItem) itr.next();
	           
	                   try {
	                           String itemName = item.getName();
	                           if (item.isFormField()) {
	                            if (item.getFieldName().equals("idevent")) {
	                                idEvent = item.getString();
	                            }
	                        }else{
	                           if ((item.getName().endsWith("png")) || ((item.getName().endsWith("jpg"))) || ((item.getName().endsWith("gif")))){
	                           
	                           adressePicture = "Pictures/" + item.getName();    
	                           File savedFile = new File(getServletContext().getRealPath("/")+"Pictures/"+itemName);
	                           item.write(savedFile);
	                                redir = "index.html";
	                           }
	                           
	                   }
	                                              
	                   } catch (Exception e1) {
	                           e1.printStackTrace();
	                   }
	    
	           
	           }
	                   // eventSessionBean.definirAdressePicture(adressePicture, idEvent);
	                    req.setAttribute("message","Votre image a bien été ajoutée.");
	                    req.getRequestDispatcher(redir).forward(req, res);

	            } catch (ValidationException v) {
	                req.setAttribute("wrongextension", v.getMessage());
	                try {
	                    req.getRequestDispatcher("AddPhoto.jsp").forward(req, res);
	                } catch (ServletException ex) {
	                    Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
	                } catch (IOException ex) {
	                    Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
	                }
	            } catch(Exception e) {
	                try {
	                    req.getRequestDispatcher("AddPhoto.jsp").forward(req, res);
	                } catch (ServletException ex) {
	                    Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
	                } catch (IOException ex) {
	                    Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
	                }
	            }
	        } else {
	            req.setAttribute("message", "Vous devez être connecté pour ajouter un event");
	            req.getRequestDispatcher("index.html").forward(req, res);
	        }

		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
